package com.xuebang.admin.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xuebang.admin.dao.Pagination;
import com.xuebang.admin.entity.MenuColumn;
import com.xuebang.admin.entity.Operator;
import com.xuebang.admin.entity.OperatorGroups;
import com.xuebang.admin.entity.OperatorRules;
import com.xuebang.admin.service.ColumnService;
import com.xuebang.admin.service.OperatorGroupsService;
import com.xuebang.admin.service.OperatorRulesService;
import com.xuebang.admin.service.OperatorService;
import com.xuebang.admin.util.JsonUtil;
import com.xuebang.admin.util.RandImage;
import com.xuebang.admin.web.Result;
import com.xuebang.admin.web.Table;


@Controller
@RequestMapping("/account")
public class AccountController extends BaseController{	

	@Inject
	private OperatorRulesService operatorRulesService ;
	@Inject
	private OperatorGroupsService operatorGroupsService ;
	@Inject
	private OperatorService operatorService ;

	@Inject
	/** 栏目业务逻辑类  */
	private ColumnService columnService;
	/** 关联栏目 */
	private StringBuilder sbRelatedColumns = new StringBuilder();
	private int intIndex = 0;
	//20140211 add by xy end

	//组织机构--账户管理
	@RequestMapping(method = RequestMethod.GET)
	public String indexOld(Table table,Operator operator,Model model) {
		if(this.hasPerm(OperatorRules.PERM_ACCOUNT)){
			return index(table,operator, model);
		}else if(this.hasPerm(OperatorRules.PERM_OPERATOR)){
			return user( table,  model);
		}else if(this.hasPerm(OperatorRules.PERM_ROLE)){
			return role(null,  table,  model);
		}else{
			return this.no_perm_page();
		}
	}
	//组织机构--账户管理
	@RequestMapping(value = "index",method = RequestMethod.GET)
	public String index(Table table,Operator operator, Model model) {

		List<OperatorGroups> operatorGroupsList = operatorGroupsService.all(false);//角色列表
		operator = operatorService.findById(this.currentOperator().getOperatorId());
		model.addAttribute("operatorGroupsList", operatorGroupsList);
		model.addAttribute("operator", operator);
		model.addAttribute("menu1", 1);
		model.addAttribute("menu2", 2);
		model.addAttribute("menu3", 2);
		model.addAttribute("menu4", 2);
		return "account/index";
	}
	@RequestMapping(value = "updateSelfSave", method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	// @ResponseBody 将内容或对象作为 HTTP 响应正文返回，并调用适合HttpMessageConverter的Adapter转换对象，写入输出流
	public @ResponseBody String updateSelfSave(Operator operator,Table table, Model model) {
		try {
			operator.setStatus("A");
			operatorService.updateSelf(operator);
			return JsonUtil.dump(Result.success("修改成功！"));
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	
	@RequestMapping(value = "getOperatorInfo", method = RequestMethod.POST)
	public @ResponseBody String getOperatorInfo(String operatorId) {
		try {
			Operator operator = operatorService.getOperatorInfo(operatorId);
			return JsonUtil.dump(operator);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	
	//组织机构--用户管理
	@RequestMapping(value = "user", method = RequestMethod.GET)
	public String user(Table table, Model model) {
		if(!this.hasPerm(OperatorRules.PERM_OPERATOR)){
			return this.no_perm_page();
		}
		
		model.addAttribute("menu1", 2);
		model.addAttribute("menu2", 1);
		model.addAttribute("menu3", 2);
		model.addAttribute("menu4", 2);
		return "account/user";
	}
	//组织机构--用户管理--人员列表查询
	@RequestMapping(value = "operators", method = RequestMethod.GET)
	public String operators(String  searchText,String departmentId,Table table, Model model) throws UnsupportedEncodingException{
		String keyWord ="";
		if(searchText==null || searchText.equals("")){
			keyWord = "";
		}else{
			keyWord = new String(searchText.getBytes("ISO-8859-1"),"UTF-8");
		}
		Pagination<Operator> paginatedList = operatorService.search(table,keyWord,departmentId);
		model.addAttribute("operators", paginatedList);
		model.addAttribute("searchText", searchText);
		model.addAttribute("page", paginatedList.page);
		model.addAttribute("totalPage", paginatedList.totalPages());
		model.addAttribute("departmentId", departmentId);
		return "account/operators";
	}
	//组织机构--用户管理--人员删除
	@RequestMapping(value = "delOperators", method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public  @ResponseBody String delOperators(String operatorIds,Model model) {
		try {
			operatorService.delOperators(operatorIds);
			return JsonUtil.dump(Result.success("删除成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	//组织机构--用户管理--新增人员
	@RequestMapping(value = "createOperator", method = RequestMethod.GET)
	public String createOperator(Operator operator,Table table, Model model) {
		List<OperatorGroups> operatorGroupsList = operatorGroupsService.all(false);//角色列表
		model.addAttribute("operatorGroupsList", operatorGroupsList);
		
		model.addAttribute("operator", operator);
		
		model.addAttribute("menu1", 2);
		model.addAttribute("menu2", 1);
		model.addAttribute("menu3", 2);
		model.addAttribute("menu4", 2);
		return "account/operator_create";
	}
	//组织机构--用户管理--新增人员保存
	@RequestMapping(value = "createOperatorSave", method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String createOperatorSave(Operator operator,Table table, Model model) {
		try {
			operator.setStatus("A");
			operator.setCreateDate(new Date());
			operatorService.create(operator);
			return JsonUtil.dump(Result.success("保存成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	//组织机构--用户管理--修改人员
	@RequestMapping(value = "updateOperator", method = RequestMethod.GET)
	public String updateOperator(String operatorId,Table table, Model model) {
		List<OperatorGroups> operatorGroupsList = operatorGroupsService.all(false);//角色列表
		model.addAttribute("operatorGroupsList", operatorGroupsList);
		
		Operator operator = operatorService.findById(Long.parseLong(operatorId));
		model.addAttribute("operator", operator);
		
		model.addAttribute("menu1", 2);
		model.addAttribute("menu2", 1);
		model.addAttribute("menu3", 2);
		model.addAttribute("menu4", 2);
		return "account/operator_update";
	}
	//组织机构--用户管理--修改人员保存
	@RequestMapping(value = "updateOperatorSave", method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String updateOperatorSave(Operator operator,Table table, Model model) {
		try {
			operator.setStatus("A");
			operator.setModifyDate(new Date());
			operatorService.update(operator);
			return JsonUtil.dump(Result.success("保存成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}

	//组织机构--角色管理
	@RequestMapping(value = "role", method = RequestMethod.GET)
	public String role(@Valid OperatorGroups operatorGroups, Table table, Model model) {
		if(!this.hasPerm(OperatorRules.PERM_ROLE)){
			return this.no_perm_page();
		}
		List<OperatorRules> operatorRulesList = operatorRulesService.all();//权限列表
		List<OperatorGroups> operatorGroupsList = operatorGroupsService.all(true);//角色列表
		
		model.addAttribute("operatorRulesList", operatorRulesList);
		model.addAttribute("operatorGroupsList", operatorGroupsList);

		model.addAttribute("operatorGroups", operatorGroups);
		model.addAttribute("menu1", 2);
		model.addAttribute("menu2", 2);
		model.addAttribute("menu3", 1);
		model.addAttribute("menu4", 2);
		// 20140211 add by xy start...
		model.addAttribute("chooseColumn",OperatorRules.PERM_ARTICLE);
		// 20140211 add by xy end...
		return "account/role";
	}

	//组织机构--角色管理-修改保存
	@RequestMapping(value = "createRoleSave", method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String createRoleSave(@Valid OperatorGroups operatorGroups,BindingResult result, Model model,RedirectAttributes redirectAttrs) {
		try {
			operatorGroups.setCreateDate(new Date());
			// 重名检查
			String strCheckResult = checkGroupName(operatorGroups.getGroupName());
			if(operatorGroups!=null && strCheckResult.equals("")){
			operatorGroupsService.create(operatorGroups);
			return JsonUtil.dump(Result.success("创建成功!"));
			// 重名检查
			} else {
				return JsonUtil.dump(Result.error(strCheckResult));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	//组织机构--角色管理-去修改页面
	@RequestMapping(value = "updateRole", method = RequestMethod.GET)
	public String updateRole(String groupId,Table table, Model model) {
		OperatorGroups operatorGroups = operatorGroupsService.findById(Long.parseLong(groupId));
		List<OperatorRules> operatorRulesList = operatorRulesService.all();//权限列表
		model.addAttribute("operatorGroups", operatorGroups);
		model.addAttribute("operatorRulesList", operatorRulesList);
		model.addAttribute("chooseColumn",OperatorRules.PERM_ARTICLE);
		model.addAttribute("menu1", 2);
		model.addAttribute("menu2", 2);
		model.addAttribute("menu3", 1);
		model.addAttribute("menu4", 2);
		return "account/role_edit";
	}
	//组织机构--角色管理-修改保存
	@RequestMapping(value = "updateRoleSave", method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String updateRoleSave(@Valid OperatorGroups operatorGroups, Model model,HttpServletRequest request) {
		try {
			operatorGroups.setModifyDate(new Date());
			// 重名检查
			String strCheckResult = checkGroupName(operatorGroups.getGroupId(),operatorGroups.getGroupName());
			if(operatorGroups!=null && strCheckResult.equals("")){
			operatorGroupsService.update(operatorGroups);
			Operator operator = (Operator)request.getSession().getAttribute("currentOperator");
			operator.setOperatorGroups(operatorGroups);
			return JsonUtil.dump(Result.success("修改成功!"));
			// 重名检查
			} else {
				return JsonUtil.dump(Result.error(strCheckResult));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	//组织机构--角色管理-删除
	@RequestMapping(value = "deleteRole", method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String deleteRole(@RequestParam String  groupId) {
		try {
			operatorGroupsService.delete(Long.parseLong(groupId));
			return JsonUtil.dump(Result.success("删除成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}

	public static class LoginForm {
		@NotEmpty
		public String name;

		@NotEmpty
		public String password;

		@NotEmpty
		public String verificationCode;
		public String keepName;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getPassword() {
			return password;
		}

		public void setPassword(String password) {
			this.password = password;
		}

		public String getVerificationCode() {
			return verificationCode;
		}

		public void setVerificationCode(String verificationCode) {
			this.verificationCode = verificationCode;
		}

		public String getKeepName() {
			return keepName;
		}

		public void setKeepName(String keepName) {
			this.keepName = keepName;
		}

	}

	// @Valid LoginForm loginForm 实体设置+类+类的引用 直接将页面传过来的production对象中的信息封装到里面去了
	@RequestMapping(value = "login", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String login(HttpServletRequest request, HttpServletResponse response, @Valid LoginForm loginForm,
			BindingResult result, Model model) {
		if (request.getMethod().equalsIgnoreCase("GET")) {
			if (currentOperator() != null) {
				return "redirect:/";
			}
			return "account/login";
		}

		/*if (result.hasErrors()) {
			model.addAttribute("message", "账号、密码、验证码不能为空");
			return "account/login";
		}
		String sRand = (String) request.getSession().getAttribute(RandImage.RAND_KEY);
		if (!loginForm.getVerificationCode().equalsIgnoreCase(sRand)) {
			model.addAttribute("message", "验证码错误");
			return "account/login";
		}
*/
		Operator operator = operatorService.login(loginForm.getName(),
				loginForm.getPassword());
		if (operator == null) {
			model.addAttribute("message", "账号、密码不匹配");
			return "account/login";
		}
		/*if("keep".equals(loginForm.getKeepName())){
			// 创建cookie
			Cookie ckName = new Cookie("keepName", loginForm.getName());
			// 保存时间，一周
			ckName.setMaxAge(1 * 7 * 24 * 60 * 60);
			// 将cookie回写到客户端
			response.addCookie(ckName);
		}else{
			// 创建cookie
			Cookie ckName = new Cookie("keepName", loginForm.getName());
			ckName.setMaxAge(0);
			// 将cookie回写到客户端
			response.addCookie(ckName);
		}*/
		operator.setLastLoginDate(new Date());
		operator.setPasswd(null);
		operatorService.update(operator);
		request.getSession().setAttribute("uid", operator.getOperatorId());
		request.getSession().setAttribute("currentOperator", operator);
		return "redirect:/account/welcome";
	}
	
	@RequestMapping(value = "welcome", method = RequestMethod.GET)
	public String welcome(Model model,HttpServletRequest request) {
		Operator currentOperator = (Operator) request.getSession().getAttribute("currentOperator");
		model.addAttribute("name",currentOperator.getName());
		model.addAttribute("menu1", 2);
		model.addAttribute("menu2", 2);
		model.addAttribute("menu3", 2);
		model.addAttribute("menu4", 2);
		return "account/welcome";
	}
	
	@RequestMapping(value = "no_perm", method = RequestMethod.GET)
	public String noPerm(Model model) {
		return this.no_perm_page();
	}

	@RequestMapping(value = "logout")
	public String logout(HttpServletRequest request) {

		request.getSession().getServletContext().removeAttribute("sessionPic");
		request.getSession().removeAttribute("uid");
		request.getSession().removeAttribute("currentOperator");
		return "redirect:/account/login";
	}
	
	//20140211 add by xy start..
	/**
	 * 栏目选择
	 */
	@RequestMapping(value="/chooseColumn",method = RequestMethod.GET)
	public String chooseColumn(Model model,String relatedColumns){

		List<MenuColumn> lstMenuColumns = columnService.loadFstColumns(false);
		// 清空
		sbRelatedColumns.setLength(0);
		intIndex = 0;
		
		for(MenuColumn menuColumn : lstMenuColumns) {
			iniRelatedColumns(0,menuColumn,intIndex,relatedColumns);
			intIndex = intIndex + 1;
		}
		if(sbRelatedColumns!=null&&!"".equals(sbRelatedColumns.toString().trim())){
			insertChildrenIndex(0);
		}

		model.addAttribute("sbRelatedColumns", sbRelatedColumns);
		return "/account/chooseColumn";
	}

	/**
	 * 准备关联栏目
	 */
	private void iniRelatedColumns(int intNumFloor,MenuColumn menuColumns,
			int intParentIndex,String relatedColumns){

		List<MenuColumn> lstTempMenuColumns = columnService.loadChildColumns(menuColumns.getId(),false);
		int i = intNumFloor;
		// title存起menuid
		sbRelatedColumns.append("<li title=\"");
		sbRelatedColumns.append(menuColumns.getId());
		sbRelatedColumns.append("\" id=\"li_" + intIndex);
		if(relatedColumns!=null && 
				relatedColumns.contains("," + menuColumns.getId() + ",")){
			sbRelatedColumns.append("\" class=\"mouse_click\">");
		} else {	
			sbRelatedColumns.append("\" class=\"mouse_cancle\">");
		}
		while(i-- > 0) {
			sbRelatedColumns.append("|--");
		}
		sbRelatedColumns.append(menuColumns.getName());
		//System.out.println("name:" + menuColumns.getMenuName());
		// 2013.12.12(A)end (value构成规则：第一个和第二个逗号之间为父index,如果无父类，则,,后面是子类index)
		sbRelatedColumns.append("<input type=\"hidden\" id=\"li_hid_"+intIndex);
		String strTmpIndex = ",";
		if(intNumFloor==0){
			strTmpIndex = strTmpIndex + ",";
		}else{
			// 
			strTmpIndex = strTmpIndex + intParentIndex  + ",";
			intParentIndex = intIndex;
		}
		sbRelatedColumns.append("\"  value=\"" + strTmpIndex);
		// 2013.12.12(A)end
		sbRelatedColumns.append("\"/></li>");
		if(lstTempMenuColumns != null && lstTempMenuColumns.size() != 0) {
			intNumFloor++;
			for(MenuColumn tempMenuColumn : lstTempMenuColumns){
				intIndex = intIndex + 1;
				iniRelatedColumns(intNumFloor,tempMenuColumn,intParentIndex,relatedColumns);
			}
		}
	}
	
	private void insertChildrenIndex(int intBeginIndex) {

		while(true){
			int intUseBeginIndex = intBeginIndex;
			String strChildIndex = "";
			int intCycleTime = 0;
			int intRecordFlagNum = 0;
			//System.out.println("ori:" + sbRelatedColumns.toString());
			while (true) {
				intCycleTime++;
				int intLiBeginIndex = sbRelatedColumns.indexOf("<li",
						intUseBeginIndex);
				// 存在<li
				if (intLiBeginIndex != -1) {
					// 得到其内容
					int intContentBeginIndex = sbRelatedColumns.indexOf(">",
							intLiBeginIndex);
					int intContentEndIndex = sbRelatedColumns.indexOf("<input",
							intLiBeginIndex);
					String strContent = sbRelatedColumns.substring(
							intContentBeginIndex + 1, intContentEndIndex);
					// |-- 的数量
					int intFlagNum = 0;
					if (strContent != null && !"".equals(strContent.trim())) {
						int intFlagBeginIndex = 0;
						while (strContent.indexOf("|--", intFlagBeginIndex) != -1) {
							intFlagBeginIndex += 3;
							intFlagNum += 1;
						}
						//System.out.println("strContent:" + strContent);
					}
					if (intCycleTime == 1) {
						intRecordFlagNum = intFlagNum;
					} else {
						// 是其子类
						if (intFlagNum - intRecordFlagNum == 1) {
							int intLiItemBeginIndex = sbRelatedColumns.indexOf(
									"li_hid_", intContentEndIndex + 6);
							int intLiItemEndIndex = sbRelatedColumns.indexOf(
									"\"", intLiItemBeginIndex);
							if (intLiItemBeginIndex != -1) {
								strChildIndex = strChildIndex
										+ sbRelatedColumns.substring(intLiItemBeginIndex+7,intLiItemEndIndex) + ",";
								//System.out.println(strChildIndex);
							}
						} else if (intFlagNum - intRecordFlagNum <= 0) {
							break;
						}
					}
					intUseBeginIndex = intContentEndIndex + 6;
				} else {
					break;
				}
			}
			// 放入
			int intValueBeginPos = sbRelatedColumns.indexOf("value=\"", intBeginIndex);
			if(intValueBeginPos!=-1){
				int intValueEndPos = sbRelatedColumns.indexOf("\"/>",intValueBeginPos);
				sbRelatedColumns.insert(intValueEndPos, strChildIndex);
				intBeginIndex = intValueEndPos;
			} else {
				break;
			}
		}
	}
	
	/**
	 * 角色重名检查
	 */
	private String checkGroupName(String groupName){
		
		if(groupName==null||groupName.trim().equals("")){
			return "角色名字不能为空";
		} else {
			List<OperatorGroups> lstOperatorGroups = operatorGroupsService.findByName(groupName);
			if(lstOperatorGroups==null||lstOperatorGroups.size()==0){
				return "";
			} else {
				return "操作失败,角色名字重复";
			}
		}
	}
	
	/**
	 * 角色重名检查
	 */
	private String checkGroupName(Long groupId,String groupName){
		
		OperatorGroups operatorGroup = operatorGroupsService.findById(groupId);
		if(operatorGroup==null){
			return "此角色不存在";
		} else {
			// 理论上不会出现这种状况
			if(operatorGroup.getGroupName()==null || operatorGroup.getGroupName().trim().equals("")){
				return checkGroupName(groupName);
			} else {
				if(operatorGroup.getGroupName().equals(groupName)){
					// 角色名字没有改变
					return "";
				} else{
					return checkGroupName(groupName);
				}
			}
		}
	}
}

